﻿using System.Collections.Generic;
using System.Device.Location;
using System.Windows;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Controls;
//using Microsoft.Phone.Controls.Maps.Core;
//using Microsoft.Phone.Controls.Maps.ConfigService;
using uottawatourguide.Helpers;

namespace uottawatourguide
{
    public partial class MainPage : PhoneApplicationPage
    {
        #region Ctor

        public MainPage()
        {
            InitializeDefaults();
            InitializeComponent();
            choseTourItem.DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);// Load tours data for the ViewModel Items

            _touchBehavior = new TouchBehavior(this);
            _touchBehavior.Tap += touchBehavior_Tap;
            _touchBehavior.Move += touchBehavior_Move;
            _touchBehavior.Hold += touchBehavior_Hold;

            _visualStates = new VisualStates(this);

            _geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            _geoWatcher.PositionChanged += Device_PositionChanged;

            mapItem.DataContext = this;


        }

        #endregion

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void ListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            //
            //Read the stops info and load it the stopsll linked list.
            //
            var selector = sender as Selector;
            if (selector == null || selector.SelectedItem == null)
            {
                return;
            }
            TourViewModel tour = selector.SelectedItem as TourViewModel;
            if(tour.Stops.IsEmpty)
                MessageBox.Show("Stops is empty");
            _stopsll = new LinkedList<StopViewModel>();
            foreach (var stop in tour.Stops.Elements("stop"))
            {
                StopViewModel s = new StopViewModel()
                {
                    
                    Title = stop.Element("title").Value,
                    Description = stop.Element("description").Value,
                    Latitude = double.Parse(stop.Element("location").Element("latitude").Value),
                    Longitude = double.Parse(stop.Element("location").Element("longitude").Value)
                };
                if (s != null)
                    _stopsll.AddLast(s);
                else
                    MessageBox.Show("Empty stop...");
            }

            //
            //Draw 
            //

            updateMap(_stopsll);
        }

        #region Fields
        LinkedList<StopViewModel> _stopsll;
        #endregion

    }
}